# 生成器generator(类似js es6)

# listGen = (item + item + 1 for item in range(1, 10))

# print(next(listGen))

# 斐波那契数列

# def fib(idx):
#     # 类似解构赋值
#     n, a, b = 0, 0, 1
#     while n < idx:
#         # 变成一个generator函数
#         yield b
#         a, b = b, a + b
#         # 没有n++
#         n = n + 1
#     return b

# print(fib(6))

# print(fib)

# 有点函数式的味道
# f = fib(6)

# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))

# 使用generator来处理异步事件等待队列

# def initConfig():
#     print('init Config..')

# def initUI():
#     print('init UI')
    # 模拟启动报错
    # a = b

# 定义启动函数
# def boot():
#     yield initConfig()
#     yield initUI()
#     yield print('start')

# startApp = boot()

# next(startApp)
# next(startApp)
# next(startApp)
# next(startApp)

# 用while语句循环generator

# while True:
#     try:
#         next(startApp)
#     # 捕获迭代器结束的异常
#     except StopIteration as error: 
#         print('App Start')
#         # 需要终止循环
#         break

# 杨辉三角

def triangles():
    n = 1
    lastArr = [1]
    while True:
        newArr = []
        for i in range(n):
            if i <= 0 or i >= n - 1:
                newArr.append(1)
            else:
                newArr.append(lastArr[i - 1] + lastArr[i])
        n = n + 1
        yield newArr
        lastArr = newArr

result = triangles()

print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))